<template>
    <view class="login_view">
        <image
            style="margin-top: 160rpx; height: 96rpx; width: 264rpx"
            src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/logo.png"
        ></image>
        <label style="margin-top: 70rpx; text-align: center; color: #333333; font-size: 36rpx; font-weight: 500"
            >倾小瘦健康小程序授权登录</label
        >
        <label style="margin-top: 20rpx; text-align: center; color: #8f909f; font-size: 28rpx; font-weight: 400"
            >使用微信账号授权登录</label
        >
        <button v-if="flag == false" class="login_btn" @click="loginEvent()">手机号授权登录</button>
        <button
            v-if="flag == true"
            class="login_btn"
            :disabled="code == ''"
            open-type="getPhoneNumber"
            @getphonenumber="phoneNumber"
        >
            手机号授权登录
        </button>
        <view class="user_terms_view">
            <image
                @click="gouxuanEvent()"
                style="width: 28rpx; height: 28rpx; margin-right: 8rpx"
                :src="
                    flag == true
                        ? 'https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/xygouxuann.png'
                        : 'https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/xygouxuan.png'
                "
            ></image>
            <label style="color: #333333; font-size: 28rpx; margin-right: 8rpx">我同意</label>
            <view @click="goToUserTerms()" style="color: #156d4f; font-size: 28rpx">《用户隐私协议》</view>
        </view>
    </view>
</template>

<script>
import { mapMutations, mapState } from "vuex";
export default {
    data() {
        return {
            iv: "",
            encryptedData: "",
            flag: false,
            code: "",
            optionsParams: {},
        };
    },
    computed: {
        ...mapState(["isLogin", "userInfo"]),
    },
    methods: {
        ...mapMutations(["loginSaveUserInfo", "logout"]),
        gouxuanEvent() {
            this.flag = !this.flag;
        },
        loginEvent() {
            if (this.flag == false) {
                uni.showToast({
                    icon: "none",
                    title: "请勾选同意用户协议",
                });
                return;
            }
        },
        phoneNumber(res) {
            if (res.detail.iv && res.detail.encryptedData) {
                this.iv = res.detail.iv;
                this.encryptedData = res.detail.encryptedData;
                this.authMobile();
            }
        },
        goToUserTerms() {
            uni.navigateTo({
                url: "./userTerms/userTerms",
            });
        },
        authMobile() {
            let data = { iv: this.iv, encryptedData: this.encryptedData, code: this.code };
            if (this.optionsParams.invitId) {
                data.inviteUserId = this.optionsParams.invitId;
            }
            console.log("authMobile", data);
            this.request.httpTokenRequest("/mp-api/wx/auth/mobile", data, "POST", false).then((res) => {
                if (res.code == 0) {
                    if (res.data.status == 1) {
                        this.loginSaveUserInfo(res.data);
                        const pages = getCurrentPages();
                        console.log("pages", pages);
                        if ((pages || []).length > 1) {
                            uni.navigateBack();
                        } else {
                            uni.switchTab({
                                url: "/pages/home/home",
                            });
                        }
                    } else {
                        if (res.data.status == 2) {
                            uni.showToast({
                                icon: "none",
                                title: "账号已被禁用，请联系管理员吧！",
                            });
                        } else {
                            uni.showToast({
                                icon: "none",
                                title: "账号异常，请联系管理员！",
                            });
                        }
                    }
                } else {
                    this.authCode();
                }
            });
        },
        authCode() {
            uni.login({
                provider: "weixin",
                success: (res) => {
                    let data = { code: res.code };
                    if (this.optionsParams.invitId) {
                        data.inviteUserId = this.optionsParams.invitId;
                    }
                    console.log("authCode", data);
                    this.code = res.code;
                    this.request.httpJsonRequest("/mp-api/wx/auth/code", data, "POST", true).then((res) => {
                        if (res.code == 0) {
                            if (res.data != null) {
                                if (res.data.uid != 0) {
                                    this.request.setToken(res.data.accessToken);
                                    this.loginSaveUserInfo(res.data);
                                }
                            }
                        }
                    });
                },
            });
        },
        /** 领取优惠券 */
        async receiveCoupon() {
            uni.showLoading({
                mask: true,
            });
            let params = {
                acceptType: 2, // 领取渠道 0.手动领取(注：普通券，商品详情处领取) 2.新人奖励
                shareUserId: this.optionsParams.invitId,
            };
            /** 当有优惠券编号时，领取前再调一次详情接口判断最新优惠券状态是否可领取 */
            if (this.optionsParams.templateNo) {
                const { data } = await this.request.httpJsonRequest(
                    `/mp-api/wx/coupon/template/detail/${this.optionsParams.templateNo}`,
                    null,
                    "GET",
                );
                /** 优惠券有库存且状态为可领取 */
                if (data.stock > 0 && data.isCanReceive) {
                    params.templateNo = this.optionsParams.templateNo;
                }
            }
            try {
                await this.request.httpTokenJsonRequest("/mp-api/wx/coupon/receive", params, "GET", true);
                uni.hideLoading();
            } catch (e) {
                //TODO handle the exception
                uni.showToast({
                    title: e.msg,
                    icon: "none",
                });
            }
            uni.switchTab({
                url: "/pages/home/home",
            });
        },
    },
    onLoad(options) {
        this.optionsParams = options;
        this.authCode();
    },
};
</script>

<style>
.user_terms_view {
    margin-top: 20rpx;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
}

.login_view {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.login_btn {
    width: 470rpx;
    height: 88rpx;
    background: linear-gradient(180deg, #46c09e 0%, #156d4f 100%);
    border-radius: 10rpx;
    line-height: 88rpx;
    text-align: center;
    color: #ffffff;
    font-size: 30rpx;
    margin-top: 220rpx;
}

.cancel_btn {
    width: 470rpx;
    height: 88rpx;
    border-radius: 10rpx;
    border: 2rpx solid #cacbd4;
    line-height: 88rpx;
    text-align: center;
    color: #464b55;
    font-size: 30rpx;
    margin-top: 20rpx;
}
</style>
